/**
 * Copyright (C) 2013 The yydorid-framework project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.yangying.androidframework.activity;

import java.util.Timer;
import java.util.TimerTask;

import net.yangying.androidframework.R;
import net.yangying.androidframework.util.Animation;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

/**
 * @author yangying
 * @date 2013-1-8 上午9:27:30
 * @version 1.0
 *
 */
public abstract class BaseActivity extends Activity {

	
	private static final String TAG = BaseActivity.class.getSimpleName();
	/**
	 * 退出提示持续时间
	 */
	private static final int EXIT_TIP_DURING = 1000;
	/**
	 * 退出提示重置时间
	 */
	private static final int EXIT_TIP_RESET = 1000;
	
	private Handler mBaseHandler;
	private ExitTip exitTip = new ExitTip();
	
	private boolean back2exit = true;
	
	private GestureDetector gestureDetector;

	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		gestureDetector=new GestureDetector(new DefaultGestureDetector());
	}

	public BaseActivity() {
		mBaseHandler = new Handler() {
			public void handleMessage(Message paramMessage) {
				switch (paramMessage.what) {
				case 0:
					break;
				default:
					break;
				}
			}
		};
	}

	@Override
    public boolean onTouchEvent(MotionEvent event){
        return gestureDetector.onTouchEvent(event);
    }
	
	protected void handleErrorEvent(String paramString) {
		if ((paramString != null) && (paramString.equalsIgnoreCase("-100"))) {
			Message localMessage = this.mBaseHandler.obtainMessage();
			localMessage.what = Integer.parseInt(paramString);
			this.mBaseHandler.sendMessage(localMessage);
		}
	}

	protected abstract void initUI();
	
	protected abstract void initListener();
	
	protected void loadData(){
		
	}
	
	protected void reloadData(){
		
	}
	
	protected void setView(int layoutId){
		setContentView(layoutId);
		initUI();
		initListener();
	}
    
    public void setPBVisibility(boolean b) {
        if(this.getParent()!=null)
            this.getParent().setProgressBarIndeterminateVisibility(b);
        else
            setProgressBarIndeterminateVisibility(b);
    }
    
    protected void setBack2Exit(boolean flag){
    	this.back2exit = flag;
    }
	/**
	 * 再按一次退出程序。
	 */
    protected void pressAgainExit() {
    	if(back2exit) {
    		if (exitTip.isExit()) {
    			Animation.set(R.anim.push_right_in, R.anim.push_right_out);
    			finish();
    		} else {
    			Toast.makeText(getApplicationContext(), R.string.msg_exit_tip,EXIT_TIP_DURING).show();
    			exitTip.doExitInOneSecond();
    		}	
    	} else {
    		Animation.set(R.anim.push_right_in, R.anim.push_right_out);
    		finish();
    	}
		
	}
	class ExitTip {
		private boolean isExit = false;
		private Runnable task = new Runnable() {
			@Override
			public void run() {
				isExit = false;
			}
		};

		public void doExitInOneSecond() {
			isExit = true;
			HandlerThread thread = new HandlerThread("doTask");
			thread.start();
			new Handler(thread.getLooper()).postDelayed(task, EXIT_TIP_RESET);
		}
		
		public boolean isExit() {
			return isExit;
		}

		public void setExit(boolean isExit) {
			this.isExit = isExit;
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			pressAgainExit();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	protected void openKeyboard() {  
		  
	     Timer timer = new Timer();  
	     timer.schedule(new TimerTask() {  
	             @Override  
	             public void run() {  
	                     InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);  
	                     imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);  
	  
	             }  
	     }, 500);  
	}
	
	protected void closeSoftKeyword(IBinder ibinder){
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
        imm.hideSoftInputFromWindow(ibinder, 0);
	}
	/**
	 * 手势操作，识别向右滑动时，关闭当前页面
	 * 
	 * @author yangying
	 * @date 2013-6-13 下午2:10:32
	 * @version 1.0
	 *
	 */
	class DefaultGestureDetector extends SimpleOnGestureListener{
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY){
            final int FLING_MIN_DISTANCE=100;//X或者y轴上移动的距离(像素)
            final int FLING_MIN_VELOCITY=200;//x或者y轴上的移动速度(像素/秒)
//            if((e1.getX()-e2.getX())>FLING_MIN_DISTANCE && Math.abs(velocityX)>FLING_MIN_VELOCITY)
//                Toast.makeText(BaseActivity.this, "向左滑动", Toast.LENGTH_SHORT).show();
//            else 
            	if((e2.getX()-e1.getX())>FLING_MIN_DISTANCE && Math.abs(velocityX)>FLING_MIN_VELOCITY){
//            		Toast.makeText(BaseActivity.this, "向右滑动", Toast.LENGTH_SHORT).show();
            		Animation.set(R.anim.push_right_in, R.anim.push_right_out);
            		finish();
            	}
                
            return false;
        }
    }
}
